﻿using CodeNotes.BLL;
using CodeNotes.Common;
using CodeNotes.Model;
using Maticsoft.Common;
using MvcCodeNotes.Models;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace MvcCodeNotes.Controllers
{
    public class AutoFetchController : Controller
    {
        JavaScriptSerializer Serializer = new JavaScriptSerializer();
        public ActionResult Index()
        {
           
            //FetchJiazhao();
            //FetchChengyu("http://chengyu.t086.com/list/A_1.html");
            //Log.LogNote("AutoFetch页面Index", "加载时间=" + DateTime.Now.ToString("yyyyMMdd hh:mm:ss"), "error");

            //遍历API列表，查看是否过期，过期则更新
            List<CW_ApiSetting> settings = new CW_ApiSettingLogic().GetModelList("1=1");
            foreach (CW_ApiSetting item in settings)
            {
                Int32 hours = Convert.ToInt32(item.IntervalHour);
                DateTime dtUpdate = Convert.ToDateTime(item.UpdateTime);
                if (dtUpdate.AddHours(hours) < DateTime.Now)
                {
                    //到更新时间了，更新接口
                    //item.ApiType
                    switch (item.ApiType)
                    {
                        case "music":
                            //启用多线程抓取数据 
                            Thread t = new Thread(new ThreadStart(FetchMusic));
                            t.Start();
                            break;
                        case "joke":
                            Thread t2 = new Thread(new ThreadStart(FetchJoke));
                            t2.Start();
                            break;
                        case "budejie":    
                            Thread t3 = new Thread(new ThreadStart(FetchBudejie));
                            t3.Start();
                            break;
                    }
                }
            }
            return View();
        }

        public ActionResult admin()
        {
            return View();
        }

        [HttpPost]
        public JsonResult SaveCook(string CookModel)
        {
            try
            {
                CookModel newModel = Serializer.Deserialize<CookModel>(CookModel);

            }
            catch (Exception ex)
            {
     
            }

            var obj = new
            {
                state = "success"
            };
            return Json(obj);
        }


        public ActionResult FetchJokeByAjax()
        {
            return View();
        }

        public ActionResult FetchVideoByAjax()
        {
            return View();
        }

        public ActionResult Other(string url)
        {
            //string url="http://chengyu.t086.com/list/A_1.html";
            //ViewBag.html = BookFetch.GetHtml("http://chengyu.t086.com/list/A_1.html", "GBK");                   
            WebClient client = new WebClient();
            string html = client.GetHtml(url);
            Regex regReplace = new Regex("<script[\\s\\S]*?>[\\s\\S]*?</script>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
            html = regReplace.Replace(html, "");
            ViewBag.html = html;

            return View();

        }

        [HttpPost]
        public JsonResult FetchList()
        {
            List<CW_FetchUrl> list = new CW_FetchUrlLogic().GetModelList("Id>=301 and Id<=400");

            var obj = new
            {
                state = "success",
                list = list
            };
            return Json(obj);
        }

        [HttpPost]
        public JsonResult WriteLog(string url, string txt, string detailUrl)
        {
            //if (new CW_IdiomLogic().GetRecordCount("Idiom='" + txt + "'") == 0)
            //{
            //    CW_Idiom model = new CW_Idiom();
            //    model.Idiom = txt;
            //    model.Url = url;
            //    model.DetailUrl = detailUrl;
            //    new CW_IdiomLogic().Add(model);
            //}

            Log.LogNote(url, txt + "==>" + detailUrl, "idiom");
            var obj = new
            {
                state = "success"
            };
            return Json(obj);
        }

        [HttpPost]
        public JsonResult SaveJoke(string type, string title, string content, string source)
        {
            try
            {
                if (type == "pic" || type == "gif")
                {
                    if (new CW_JokePictureLogic().GetRecordCount("Content='" + content + "'") == 0)
                    {
                        CW_JokePicture pic = new CW_JokePicture
                        {
                            Title = title,
                            Content = content,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            IsShow = true,
                            Source = source
                        };
                        new CW_JokePictureLogic().Add(pic);
                    }
                }
                else if (type == "txt")
                {
                    if (new CW_JokeLogic().GetRecordCount("Content='" + content + "'") == 0)
                    {
                        //使用js的unescape进行解码

                        CW_Joke pic = new CW_Joke
                        {
                            Title = Microsoft.JScript.GlobalObject.unescape(title),
                            Content = Microsoft.JScript.GlobalObject.unescape(content),
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now,
                            IsShow = true,
                            Source = source
                        };
                        new CW_JokeLogic().Add(pic);
                    }
                }

            }
            catch (Exception ex)
            {
                Log.LogNote("获取Joke", string.Format("title={0},content={1},source={2},error={3}", title, content, source, ex.Message.ToString()), "joke");
            }

            ////使用js的unescape进行解码
            //Microsoft.JScript.GlobalObject.escape("");
            //Microsoft.JScript.GlobalObject.unescape(""); 

            var obj = new
            {
                state = "success"
            };
            return Json(obj);
        }


        [HttpPost]
        public JsonResult SaveVideo(string type, string vid, string url, string title, string desc, string pic)
        {
            try
            {

                if (new CW_JokeVideoLogic().GetRecordCount("vid='" + vid + "'") == 0)
                {
                    CW_JokeVideo video = new CW_JokeVideo
                    {
                        Vid = vid,
                        Title = title,
                        Description = desc,
                        Pic = pic,
                        CreateTime = DateTime.Now,
                        IsShow = true,
                        Source = url,
                        TagId = 1,
                        Sort = 0
                    };
                    new CW_JokeVideoLogic().Add(video);
                }



            }
            catch (Exception ex)
            {
                Log.LogNote("获取Joke", string.Format("title={0},vid={1},url={2},desc={3},error={4}", title, vid, url, desc, ex.Message.ToString()), "jokeVideo");
            }

            var obj = new
            {
                state = "success"
            };
            return Json(obj);
        }



        public void FetchChengyu(string url)
        {
            bool isError = false;
            string errorMsg = "";
            try
            {
                string siteHost = "http://chengyu.t086.com/list/";
                string html = BookFetch.GetHtml(url, "GBK");
                Regex regReplace = new Regex("<script[\\s\\S]*?>[\\s\\S]*?</script>", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                html = regReplace.Replace(html, "").Replace("&lt;div id=&quot;ad_250_left&quot;&gt;&lt;/div&gt;", "");

                //string pattern = "<a\\s+href=\"(http://www.8dushu.com)?(?<sorturl>/sort\\d+/\\d+/)\">(?<sortname>[^<]+)</a>";

                string pattern = "[A-Z]_\\d+\\.html";

                MatchCollection mContent = Regex.Matches(html, pattern);
                if (mContent.Count > 0)
                {
                    for (int i = 0; i < mContent.Count; i++)
                    {
                        string tempurl = mContent[i].Value;
                        if (tempurl != "")
                        {
                            //判断此网址是否已保存
                            string fetchUrl = siteHost + tempurl;
                            int existCount = new CW_FetchUrlLogic().GetRecordCount("Url='" + fetchUrl + "'");
                            if (existCount == 0)
                            {
                                CW_FetchUrl fetch = new CW_FetchUrl();
                                fetch.SiteName = siteHost;
                                fetch.BookName = tempurl;
                                fetch.Url = fetchUrl;
                                fetch.Encoding = "GBK";
                                fetch.IsBookOver = false;
                                fetch.IsFetch = false;
                                fetch.CreateTime = DateTime.Now;
                                new CW_FetchUrlLogic().Add(fetch);
                                FetchChengyu(fetchUrl);
                            }
                        }
                    }
                }
                else
                {
                    isError = true;
                    errorMsg = "正则没匹配到数据";
                }
            }
            catch (Exception ex)
            {
                isError = true;
                errorMsg = ex.Message.ToString();
            }
            if (isError)
            {
                CW_BookFetchLog log = new CW_BookFetchLog();
                log.BookName = "";
                log.FetchUrl = url;
                log.ErrorMsg = errorMsg;
                log.CreateDate = DateTime.Now;
                new CW_BookFetchLogLogic().Add(log);
            }

        }

        private void FetchMusic()
        {
            string url = "http://route.showapi.com/213-4?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&topid=26";
            try
            {

                CW_MusicLogic logic = new CW_MusicLogic();
                string EncodingStr = "UTF-8";
                string html = BookFetch.GetHtml(url, EncodingStr);
                JavaScriptSerializer Serializer = new JavaScriptSerializer();
                ShowapiModel result = Serializer.Deserialize<ShowapiModel>(html);

                bool isUpdate = false;
                if (result.showapi_res_body != null && result.showapi_res_body.pagebean != null && result.showapi_res_body.pagebean.songlist != null)
                {
                    List<SongModel> songlist = result.showapi_res_body.pagebean.songlist;
                    DataTable dtAll = logic.GetAllList().Tables[0];
                    string ids = "";
                    foreach (SongModel song in songlist)
                    {
                        //判断歌曲是否存在
                        DataRow[] drs = dtAll.Select("songid=" + song.songid);
                        int existNum = drs.Length;
                        if (existNum == 0)
                        {
                            CW_Music newSong = new CW_Music();
                            newSong.albumid = song.albumid;
                            newSong.albummid = song.albummid;
                            newSong.albumpic = song.albumpic_small;
                            newSong.downUrl = song.downUrl;
                            newSong.seconds = song.seconds;
                            newSong.singerid = song.singerid;
                            newSong.singername = song.singername;
                            newSong.songid = song.songid;
                            newSong.songname = song.songname;
                            newSong.url = song.url;
                            newSong.CreateTime = DateTime.Now;
                            int id = logic.Add(newSong);
                            ids += id + ",";
                            isUpdate = true;
                        }
                        else
                        {
                            ids += drs[0]["Id"].ToString() + ",";
                        }

                    }

                    CW_ApiSetting musicSetting = new CW_ApiSettingLogic().GetModelList("ApiType='music'")[0];
                    if (isUpdate)
                    {
                        musicSetting.Version = DateTime.Now.ToString("yyyyMMddHHmmss");
                        musicSetting.Json = ids;
                    }

                    musicSetting.FetchCount = musicSetting.FetchCount + 1;
                    musicSetting.UpdateTime = DateTime.Now;
                    new CW_ApiSettingLogic().Update(musicSetting);
                }
            }
            catch (Exception ex)
            {
                Log.LogNote("AutoFetch--Music", "抓取报错=" + DateTime.Now.ToString("yyyyMMdd hh:mm:ss") + "   " + ex.Message.ToString(), "error");
                CW_BookFetchLog model = new CW_BookFetchLog();
                model.BookName = "AutoFetch--MUSIC";
                model.FetchUrl = url;
                model.ErrorMsg = ex.Message.ToString();
                model.CreateDate = DateTime.Now;
                new CW_BookFetchLogLogic().Add(model);
            }

        }

        //抓取笑话
        private void FetchJoke()
        {            
            string EncodingStr = "UTF-8";
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            string url1 = "http://route.showapi.com/341-1?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&maxResult=50&page=1";
            string url2 = "http://route.showapi.com/341-2?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&maxResult=50&page=1";
            string url3 = "http://route.showapi.com/341-3?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&maxResult=50&page=1";
            try
            {
                string html1 = BookFetch.GetHtml(url1, EncodingStr);
                ShowapiModel result1 = Serializer.Deserialize<ShowapiModel>(html1);
                if (result1.showapi_res_body != null && result1.showapi_res_body.contentlist != null)
                {
                    CW_JokeLogic logic = new CW_JokeLogic();
                    List<JokeModel> jokelist = result1.showapi_res_body.contentlist;                    
                    foreach (JokeModel joke in jokelist)
                    {
                        //判断是否存在
                        if (logic.GetRecordCount("Content='" + joke.text + "'") == 0)
                        {
                            CW_Joke pic = new CW_Joke
                            {
                                Title = joke.title,
                                Content = joke.text,
                                CreateTime = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                IsShow = true,
                                Source = "showapi"
                            };
                            logic.Add(pic);
                        }
                    }                    
                }

                string html2 = BookFetch.GetHtml(url2, EncodingStr);
                ShowapiModel result2 = Serializer.Deserialize<ShowapiModel>(html2);
                if (result2.showapi_res_body != null && result2.showapi_res_body.contentlist != null)
                {
                    CW_JokePictureLogic logic = new CW_JokePictureLogic();
                    List<JokeModel> jokelist = result2.showapi_res_body.contentlist;                    
                    foreach (JokeModel joke in jokelist)
                    {
                        //判断是否存在
                        if (logic.GetRecordCount("Content='" + joke.img + "'") == 0)
                        {
                            CW_JokePicture pic = new CW_JokePicture
                            {
                                Title = joke.title,
                                Content = joke.img,
                                CreateTime = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                IsShow = true,
                                Source = "showapi"
                            };
                            logic.Add(pic);
                        }
                    }
                }

                string html3 = BookFetch.GetHtml(url3, EncodingStr);
                ShowapiModel result3 = Serializer.Deserialize<ShowapiModel>(html3);
                if (result3.showapi_res_body != null && result3.showapi_res_body.contentlist != null)
                {
                    CW_JokePictureLogic logic = new CW_JokePictureLogic();
                    List<JokeModel> jokelist = result3.showapi_res_body.contentlist;
                    foreach (JokeModel joke in jokelist)
                    {
                        //判断是否存在
                        if (logic.GetRecordCount("Content='" + joke.img + "'") == 0)
                        {
                            CW_JokePicture pic = new CW_JokePicture
                            {
                                Title = joke.title,
                                Content = joke.img,
                                CreateTime = DateTime.Now,
                                UpdateTime = DateTime.Now,
                                IsShow = true,
                                Source = "showapi"
                            };
                            logic.Add(pic);
                        }
                    }
                }

                CW_ApiSetting musicSetting = new CW_ApiSettingLogic().GetModelList("ApiType='joke'")[0];
                musicSetting.Version = DateTime.Now.ToString("yyyyMMddHHmmss");
                musicSetting.FetchCount = musicSetting.FetchCount + 1;
                musicSetting.UpdateTime = DateTime.Now;
                new CW_ApiSettingLogic().Update(musicSetting);

            }
            catch (Exception ex)
            {
            }

        }

        //抓取百思不得姐
        private void FetchBudejie()
        {
            string EncodingStr = "UTF-8";
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            string url = "http://route.showapi.com/255-1?showapi_sign=3f0c698c4357477ba780198b22f4eeaf&showapi_appid=35037&maxResult=50&page=1";
            try
            {
                string html = BookFetch.GetHtml(url, EncodingStr);
                ShowapiModel result = Serializer.Deserialize<ShowapiModel>(html);
                 if (result.showapi_res_body != null && result.showapi_res_body.pagebean != null && result.showapi_res_body.pagebean.contentlist != null)
                {
                
                    CW_JokePictureLogic logicPic = new CW_JokePictureLogic();
                    CW_JokeVideoLogic logicVideo = new CW_JokeVideoLogic();

                    List<SongModel> jokelist = result.showapi_res_body.pagebean.contentlist;
                    foreach (SongModel joke in jokelist)
                    {
                        joke.text = joke.text.Replace("\n", "").Replace("\n", "").Trim();
                        if(joke.type=="10")
                        {
                            //判断是否存在
                            if (logicPic.GetRecordCount("Content='" + joke.image0 + "'") == 0)
                            {
                                CW_JokePicture pic = new CW_JokePicture
                                {
                                    Title = joke.text,
                                    Content = joke.image0,
                                    CreateTime = DateTime.Now,
                                    UpdateTime = DateTime.Now,
                                    IsShow = true,
                                    Source = "budejie"
                                };
                                logicPic.Add(pic);
                            }

                        }
                        else if (joke.type == "41")
                        {
                            //判断是否存在
                            if (logicVideo.GetRecordCount("Pic='" + joke.video_uri + "'") == 0)
                            {
                                CW_JokeVideo pic = new CW_JokeVideo
                                {
                                    Title = joke.text,
                                    Pic = joke.video_uri,
                                    CreateTime = DateTime.Now,
                                    TagId=2,
                                    IsShow = true,
                                    Source = "budejie"
                                };
                                logicVideo.Add(pic);
                            }

                        }
                       
                    }
                }

                CW_ApiSetting musicSetting = new CW_ApiSettingLogic().GetModelList("ApiType='budejie'")[0];
                musicSetting.Version = DateTime.Now.ToString("yyyyMMddHHmmss");
                musicSetting.FetchCount = musicSetting.FetchCount + 1;
                musicSetting.UpdateTime = DateTime.Now;
                new CW_ApiSettingLogic().Update(musicSetting);

            }
            catch (Exception ex)
            {
            }

        }


        //type=1位科目一，type=2为科目四
        //如果sohuimg不为空 http://img.itc.cn/photo/{sohuimg}_w320
        //if (typeof o.sohuimg != "undefined" && o.sohuimg != "") {
        //       return temp.replace("{image}", "//img.itc.cn/photo/" + o.sohuimg + "_w320")
        //  } else {
        //     return temp.replace("{image}", imageurl)
        //   }
        // mp4地址：//sdl.58cdn.com.cn/jxedt/video/excersizevideo/_40004.mp4

        private void FetchJiazhao()
        {
            for (int i = 2212; i <= 2730; i++)
            {
                string url = "http://m.jxedt.com/mnksnew/g.asp?id=" + i;
                string EncodingStr = "UTF-8";
                string html = BookFetch.GetHtml(url, EncodingStr);
                html = html.Replace("\\", "");
                if (!string.IsNullOrEmpty(html) && html.IndexOf("DOCTYPE") == -1)
                {
                    try
                    {
                        JavaScriptSerializer Serializer = new JavaScriptSerializer();
                        CW_JiaZhao result = Serializer.Deserialize<CW_JiaZhao>(html);
                        if (result != null)
                        {
                            result.id = 0;
                            new CW_JiaZhaoLogic().Add(result);
                        }
                    }
                    catch (Exception ee)
                    {
                    }

                }

            }


        }

    }
}
